import { readFileSync, readdirSync } from "fs";
import path from "path";

// 识别svg标签的属性
const svgTitle = /<svg([^>+].*?)>/;

// 有一些svg文件的属性会定义height和width，要把它清除掉
const clearHeightWidth = /(width|height)="([^>+].*?)"/g;

// 没有viewBox的话就利用height和width来新建一个viewBox
const hasViewBox = /(viewBox="[^>+].*?")/g;

// 清除换行符
const clearReturn = /(\r)|(\n)/g;

/**
 * @param dir 路径
 */
function svgs2SymbolFile(dir) {
  const symbolRes = [];
  const dirents = readdirSync(dir, {
    withFileTypes: true,
  });
  for (const dirent of dirents) {
    const svg = readFileSync(path.join(dir, dirent.name))
      .toString()
      .replace(clearReturn, "")
      .replace(svgTitle, ($1, $2) => {
        let width = 0;
        let height = 0;
        let content = $2.replace(clearHeightWidth, (s1, s2, s3) => {
          s3 = s3.replace("px", "");
          if (s2 === "width") {
            width = s3;
          } else if (s2 === "height") {
            height = s3;
          }
          return "";
        });
        if (!hasViewBox.test($2)) {
          content += `viewBox="0 0 ${width} ${height}"`;
        }
        return `<symbol id="${dirent.name.replace(".svg", "")}" ${content}>`;
      })
      .replace("</svg>", "</symbol>");
    symbolRes.push(svg);
  }
  return symbolRes;
}

export default svgs2SymbolFile;
